package qingma

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/oceanengine/ad_open_sdk_go/models"
	"google.golang.org/grpc/status"
	"io"
	"log"
	"net/http"
	"qm_system_server/server/global"
	"qm_system_server/server/model/common/response"
	"qm_system_server/server/proto/grpc/huge"
	"qm_system_server/server/proto/grpc/operate"
	"strconv"
)

type HugeApi struct {
}

func getHttp(params map[string]interface{}, apiUrl string, c *gin.Context) {
	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.CommonApi().Get(ctx, apiUrl).
		AccessToken(accessToken).
		RequestQuery(params).Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err := json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

func postHttp(params map[string]interface{}, apiUrl string, c *gin.Context) {
	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.CommonApi().Post(ctx, apiUrl).
		AccessToken(accessToken).
		RequestBody(params).Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err := json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

func getToken() string {
	client := huge.NewHugeServiceClient(global.OperateGrpc)
	resp, err := client.GetAccessToken(context.Background(), &huge.TokenRequest{
		PlatformId: "1",
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			return st.Message()
		}
		return ""
	}
	return resp.AccessToken
}

func (h *HugeApi) GetHugeData(c *gin.Context) {
	type request struct {
		// 请求参数
		GameHash   string `json:"game_hash" from:"game_hash"`
		Type       string `json:"type" form:"type"`
		StartDate  string `json:"start_date" form:"start_date"`
		EndDate    string `json:"end_date" form:"end_date"`
		PlatformId int64  `json:"platform_id" form:"platform_id"`
		Params     string `json:"params" form:"params"`
		Page       int64  `json:"page" form:"page"`
		Flag       int64  `json:"flag" form:"flag"`
		AddParams  string `json:"add_params" form:"add_params"`
	}

	var req request
	var platformId string

	c.ShouldBindQuery(&req)

	req.GameHash = c.Request.Header.Get("game-hash")

	if req.Flag == 0 {
		platformId = c.Request.Header.Get("platform-id")
		if platformId != "" {
			req.PlatformId, _ = strconv.ParseInt(platformId, 10, 64)
		}
	}

	grpcClient := operate.NewOperateServiceClient(global.OperateGrpc)

	resp, err := grpcClient.ShowData(context.Background(), &operate.ShowDataRequest{
		GameHash:   req.GameHash,
		Type:       req.Type,
		StartDate:  req.StartDate,
		EndDate:    req.EndDate,
		PlatformId: req.PlatformId,
		Params:     req.Params,
		Page:       req.Page,
		AddParams:  req.AddParams,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(response.PageResult{
		List:   resp.List,
		Total:  resp.Total,
		Page:   int(req.Page),
		Result: resp.Result,
	}, c)
}

func (h *HugeApi) GetDistrictList(c *gin.Context) {
	type GetDistrictListReq struct {
		AdvertiserId int64                              `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Codes        string                             `json:"codes,omitempty" form:"codes"`
		Language     models.ToolsAdminInfoV2Language    `json:"language,omitempty" form:"language"`
		SubDistrict  models.ToolsAdminInfoV2SubDistrict `json:"sub_district,omitempty" form:"sub_district"`
	}

	var request GetDistrictListReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"codes":         request.Codes,
		"language":      request.Language,
		"sub_district":  request.SubDistrict,
	}
	getHttp(params, "/open_api/2/tools/admin/info/", c)
}

func (h *HugeApi) GetSuggestWords(c *gin.Context) {
	type GetSuggestWordsReq struct {
		AdvertiserId int64    `json:"advertiser_id,omitempty" form:"advertiser_id"`
		QueryList    []string `json:"query_list,omitempty" form:"query_list"`
	}
	var request GetSuggestWordsReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"query_list":    request.QueryList,
	}

	postHttp(params, "/open_api/v3.0/sugg_words/", c)
}
